<script setup lang="ts">
import type {
  SysDeptTreeVo,
} from '#/system/dept'
import type {
  TreeInstance,
} from 'element-plus'
import {
  getSysDeptTreeApi,
} from '@/api/system/dept'
import {
  Search,
} from '@element-plus/icons-vue'

let deptTree = $ref<SysDeptTreeVo[]>()
const filterText = $ref('')
const treeRef = $ref<TreeInstance>()
const modelVal = defineModel()

function getDeptTree() {
  getSysDeptTreeApi().then((res) => {
    deptTree = res.data
  })
}

function nodeClick(data: SysDeptTreeVo) {
  modelVal.value = data.id
}

function filterNode(value: string, data: SysDeptTreeVo) {
  if (!value)
    return true
  return data.name?.includes(value) || false
}

watch(() => filterText, (val) => {
  if (!treeRef)
    return
  treeRef.filter(val)
})

watch(() => modelVal, () => {
  if (!treeRef)
    return
  treeRef.setCurrentKey(modelVal.value as any)
}, {
  deep: true,
  immediate: true,
})

onMounted(() => {
  getDeptTree()
})
</script>

<template>
  <el-scrollbar>
    <el-card>
      <el-input
        v-model="filterText"
        placeholder="请输入部门名称"
        clearable
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
      </el-input>
      <el-tree
        ref="treeRef"
        un-m-t="2"
        :data="deptTree"
        :props="{
          label: 'name',
        }"
        node-key="id"

        :filter-node-method="filterNode"
        highlight-current default-expand-all
        :expand-on-click-node="false"
        @node-click="nodeClick"
      />
    </el-card>
  </el-scrollbar>
</template>

<style scoped></style>
